package com.gjb6.master.app;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.gjb6.master.R;
import com.gjb6.master.account.AccountManager;
import com.gjb6.master.account.Login.LoginActivity;
import com.gjb6.master.app.storagemanager.SpDao;
import com.gjb6.master.utils.ProviderUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;

import static com.gjb6.master.app.MainActivity.REQ_CODE_READ_LOCATION;

public class MySplashActivity extends BaseActivity {
    Handler handler = new Handler();
    private boolean mIsFirstStart;
    Intent intent;
    private double latitude;
    private double longitude;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideToolbar();
        initMap();
        checkPermission();

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        }
        mIsFirstStart = SpDao.isFirstTimeStartApp(this);
        Log.e("mIsFirstStart",mIsFirstStart+"");
        initActivity();
    }

    private void initMap() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplication());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //启动定位
        mLocationClient.startLocation();
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {

            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    latitude = amapLocation.getLatitude();
                    longitude = amapLocation.getLongitude();
                    String s = longitude + "," + latitude;
                    Log.e("sssss",s);
                    AccountManager.getCurrentAccount().setLongitude(s);
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                    //可在其中解析amapLocation获取相应内容。
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                    EasyToast.showToast(MySplashActivity.this, amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void checkPermission() {
        final int apiLevel = Build.VERSION.SDK_INT;
        if(apiLevel>=23){//判断6.0以上的手机
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            REQ_CODE_READ_LOCATION);
                }
            } else {
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQ_CODE_READ_LOCATION){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
            } else {
                // Permission Denied
                //  displayFrameworkBugMessageAndExit();
                Toast.makeText(this, "请在应用管理中打开“定位”访问权限！", Toast.LENGTH_LONG).show();
                showPermissionsDialog();
            }
        }
    }

    private void showPermissionsDialog() {

        AlertDialogFragment permissDialogFrag = new AlertDialogFragment();
        permissDialogFrag.setMessage("您未允许获得定位权限，您可在系统设置中开启")
                .setNegativeButton("暂不", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        permissDialogFrag.dismiss();
                    }
                })
                .setPositiveButton("去设置", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ProviderUtils.showInstalledAppDetails(MySplashActivity.this,"com.gjb6.master");
                        permissDialogFrag.dismiss();
                    }
                })
                .show(getSupportFragmentManager());
    }
    private void initActivity() {
        intent = new Intent();
        handler.postDelayed(new Runnable() {
            public void run() {
                if (mIsFirstStart) {
                    intent.setClass(MySplashActivity.this, MyGuideActivity.class);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    startActivity(intent);
                    finish();
                    SpDao.setKeyFirstTimeStartApp(MySplashActivity.this, false);
                } else {
                    intent.setClass(MySplashActivity.this, LoginActivity.class);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    startActivity(intent);
                    finish();
                }
            }
        }, 1500);
    }

    /**
     * 隐藏标题栏， 不论是custom的还是toolbar
     */
    public void hideToolbar() {
        View customToolbar = getCustomToolbar();
        if (customToolbar != null && customToolbar.getVisibility() == View.VISIBLE) {
            customToolbar.setVisibility(View.GONE);
        }

        if (getToolbar() != null && getToolbar().getVisibility() == View.VISIBLE) {
            getToolbar().setVisibility(View.GONE);
        }
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_my_splash,null);
    }
}
